<template>
  <div class="app-container">
    <!-- 报表类型选择 -->
    <el-card class="search-card">
      <el-form>
        <el-form-item label="报表类型">
          <el-select v-model="reportType" placeholder="请选择报表类型" style="width: 300px">
            <el-option 
              v-for="item in reportTypeOptions" 
              :key="item.dictValue" 
              :label="item.dictLabel" 
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 站点配置 -->
    <el-card class="site-config-card mt-2">
      <template #header>
        <div class="card-header">
          <span>站点配置</span>
          <span class="selected-count">已选择{{ selectedSites.length }}个站点</span>
        </div>
      </template>
      
      <div class="site-selection">
        <el-checkbox 
          v-model="selectAll" 
          :indeterminate="isIndeterminate" 
          @change="handleSelectAll"
        >
          全选
        </el-checkbox>
        
        <div class="site-list">
          <el-checkbox-group v-model="selectedSites" @change="handleSiteChange">
            <div class="site-item" v-for="site in siteList" :key="site.siteAdminId">
              <el-checkbox :label="site.siteAdminId">
                <div class="site-info">
                  <span class="site-name">{{ site.siteName }}</span>
                  <span class="site-id">站点ID: {{ site.siteCode }}</span>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
      </div>
    </el-card>

    <!-- 统计项-监测量映射 -->
    <el-card class="mapping-config-card mt-2">
      <template #header>
        <div class="card-header">
          <span>统计项-监测量映射</span>
          <el-button type="primary" size="small" @click="handleAddMapping">
            <el-icon><Plus /></el-icon>新增映射
          </el-button>
        </div>
      </template>
      
      <el-table :data="waterQualityList" border style="width: 100%" v-loading="mappingLoading">
        <el-table-column prop="statName" label="统计项名称" align="center" />
        <el-table-column prop="metricCode" label="对应监测量ID" align="center" />
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row, $index }">
            <el-button size="small" type="danger" @click="handleDeleteMapping(row, $index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 水质限值配置 -->
    <el-card class="water-quality-card mt-2">
      <template #header>
        <div class="card-header">
          <span>水质限值配置</span>
        </div>
      </template>
      
      <el-table :data="waterQualityList" border style="width: 100%" v-loading="waterQualityLoading">
        <el-table-column prop="statName" label="水质指标名称" align="center" />
        <el-table-column prop="upperLimit" label="上限值" align="center" />
        <el-table-column prop="lowerLimit" label="下限值" align="center" />
        <el-table-column prop="unit" label="单位" align="center" />
        <!-- <el-table-column label="操作" width="100" align="center">
          <template #default="{ row, $index }">
            <el-button size="small" type="danger" @click="handleDeleteWaterQuality(row, $index)">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>
    </el-card>

    <!-- 保存按钮 -->
    <!-- <div class="action-buttons mt-2">
      <el-button type="primary" size="large" @click="handleSaveConfig" :loading="saving">保存配置</el-button>
    </div> -->

    <!-- 新增映射对话框 -->
    <el-dialog v-model="mappingDialog.visible" title="新增统计项-监测量映射" width="500px">
      <el-form :model="mappingForm" :rules="mappingRules" ref="mappingFormRef" label-width="100px">
        <el-form-item label="统计项名称" prop="statName">
          <el-input v-model="mappingForm.statName" placeholder="请输入统计项名称" />
        </el-form-item>
        <el-form-item label="监测量" prop="metricCode">
          <el-select v-model="mappingForm.metricCode" placeholder="请选择监测量" filterable style="width: 100%">
            <el-option 
              v-for="item in monitoringList" 
              :key="item.monitorCode" 
              :label="`${item.monitorName} (${item.monitorCode})`" 
              :value="item.monitorCode" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="mappingDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmMapping" :loading="mappingDialog.loading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'  
import { Plus } from '@element-plus/icons-vue'

// API接口
import {
  getReportTypeList,
  getSiteList,
  getMonitoringList,
  addMapping,
  getWaterQualityLimit,
  deleteMapping
} from '@/api/dispatch/affair/reportSetting'

// 响应式数据
const reportType = ref('')
const selectAll = ref(false)
const isIndeterminate = ref(false)
const selectedSites = ref([])
const saving = ref(false)

// 加载状态
const mappingLoading = ref(false)
const waterQualityLoading = ref(false)

// 数据存储
const reportTypeOptions = ref([])
const siteList = ref([])
const monitoringList = ref([])
const mappingList = ref([])
const waterQualityList = ref([])

// 对话框控制
const mappingDialog = reactive({
  visible: false,
  loading: false
})

const mappingFormRef = ref()

// 表单数据
const mappingForm = reactive({
  statName: '',
  metricCode: ''
})

// 表单验证规则
const mappingRules = reactive({
  statName: [
    { required: true, message: '请输入统计项名称', trigger: 'blur' }
  ],
  metricCode: [
    { required: true, message: '请选择监测量', trigger: 'change' }
  ]
})

// 计算属性
const selectedCount = computed(() => selectedSites.value.length)

// 初始化加载数据
onMounted(() => {
  loadAllData()
})

// 加载所有数据
const loadAllData = async () => {
  try {
    await Promise.all([
      loadReportTypeList(),
      loadSiteList(),
      loadMonitoringList(),
      loadWaterQualityLimit()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 加载报表类型列表
const loadReportTypeList = async () => {
  try {
    const res = await getReportTypeList()
    // 根据接口文档，返回的是数组格式
    reportTypeOptions.value = res || []
  } catch (error) {
    console.error('加载报表类型列表失败:', error)
    throw error
  }
}

// 加载站点列表
const loadSiteList = async () => {
  try {
    const res = await getSiteList()
    // 根据接口文档，返回格式为 { code, msg, data }
    siteList.value = res.data || []
  } catch (error) {
    console.error('加载站点列表失败:', error)
    throw error
  }
}

// 加载监测量列表
const loadMonitoringList = async () => {
  try {
    const res = await getMonitoringList()
    // 根据接口文档，返回格式为 { code, msg, data }
    monitoringList.value = res.data || []
  } catch (error) {
    console.error('加载监测量列表失败:', error)
    throw error
  }
}

// 加载水质限值配置
const loadWaterQualityLimit = async () => {
  try {
    waterQualityLoading.value = true
    const res = await getWaterQualityLimit()
    // 根据接口文档，返回格式为 { code, msg, data }
    waterQualityList.value = res.data || []
  } catch (error) {
    console.error('加载水质限值配置失败:', error)
    throw error
  } finally {
    waterQualityLoading.value = false
  }
}

// 全选/取消全选
const handleSelectAll = (val) => {
  selectedSites.value = val ? siteList.value.map(site => site.siteAdminId) : []
  isIndeterminate.value = false
}

// 站点选择变化
const handleSiteChange = (value) => {
  const checkedCount = value.length
  selectAll.value = checkedCount === siteList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < siteList.value.length
}

// 新增映射
const handleAddMapping = () => {
  mappingDialog.visible = true
  // 重置表单
  Object.assign(mappingForm, {
    statName: '',
    metricCode: ''
  })
  // 清除验证
  if (mappingFormRef.value) {
    mappingFormRef.value.clearValidate()
  }
}

// 确认新增映射
const handleConfirmMapping = async () => {
  try {
    // 表单验证
    await mappingFormRef.value.validate()
    
    mappingDialog.loading = true
    
    // 调用新增映射接口
    const mappingData = {
      statName: mappingForm.statName,
      metricCode: mappingForm.metricCode
    }
    
    await addMapping(mappingData)
    
    // 重新加载映射数据
    await loadWaterQualityLimit()
    
    mappingDialog.visible = false
    ElMessage.success('新增映射成功')
  } catch (error) {
    if (error && error.fields) {
      // 表单验证失败
      return
    }
    console.error('新增映射失败:', error)
    ElMessage.error('新增映射失败')
  } finally {
    mappingDialog.loading = false
  }
}

// 删除映射
const handleDeleteMapping = async (row, index) => {
  try {
    await ElMessageBox.confirm(`确定删除映射 "${row.statName}" 吗？`, '提示', {
      type: 'warning'
    })
    
    // 由于接口文档中没有提供删除映射的接口，这里只从前端移除
    // 实际项目中应该调用删除接口
    // mappingList.value.splice(index, 1)
    await deleteMapping(row.id)
    loadAllData();
    ElMessage.success('删除映射成功')
  } catch {
    // 用户取消删除
  }
}

// 删除水质限值配置
const handleDeleteWaterQuality = async (row, index) => {
  try {
    await ElMessageBox.confirm(`确定删除水质限值配置 "${row.statName}" 吗？`, '提示', {
      type: 'warning'
    })
    
    // 由于接口文档中没有提供删除水质限值的接口，这里只从前端移除
    // 实际项目中应该调用删除接口
    waterQualityList.value.splice(index, 1)
    ElMessage.success('删除水质限值配置成功')
  } catch {
    // 用户取消删除
  }
}

// 保存配置
const handleSaveConfig = async () => {
  if (!reportType.value) {
    ElMessage.warning('请选择报表类型')
    return
  }

  if (selectedSites.value.length === 0) {
    ElMessage.warning('请至少选择一个站点')
    return
  }

  try {
    saving.value = true
    
    // 准备保存数据
    const saveData = {
      reportType: reportType.value,
      selectedSites: selectedSites.value,
      mappings: mappingList.value,
      waterQualityConfig: waterQualityList.value
    }
    
    console.log('保存配置数据:', saveData)
    
    // 由于接口文档中没有提供保存配置的完整接口，这里模拟保存过程
    // 实际项目中应该调用保存接口
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('配置保存成功')
    
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

.selected-count {
  color: #606266;
  font-size: 14px;
}

.mt-2 {
  margin-top: 20px;
}

.site-selection {
  padding: 20px;
}

.site-list {
  margin-top: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  background: white;
}

.site-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.site-item:last-child {
  border-bottom: none;
}

.site-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.site-name {
  font-weight: 500;
  color: #303133;
}

.site-id {
  color: #909399;
  font-size: 12px;
}

:deep(.el-checkbox) {
  width: 100%;
}

:deep(.el-checkbox__label) {
  width: 100%;
}

.action-buttons {
  text-align: center;
  padding: 20px;
  background: white;
  border-radius: 4px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .cell) {
  padding: 8px 12px;
}

:deep(.el-card__header) {
  padding: 0;
}

:deep(.el-card__body) {
  padding: 20px;
}

.search-card,
.site-config-card,
.mapping-config-card,
.water-quality-card {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .site-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .selected-count {
    align-self: flex-end;
  }
}
</style>